package com.itheima.service.impl;
import com.google.common.collect.Maps;
import com.itheima.utils.GrantTypeEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.function.Function;

@Service
public class QueryGrantTypeService implements InitializingBean {

    private final Map<Integer, Function<Integer, String>> grantTypeMap = Maps.newConcurrentMap();

    @Autowired
    private GrantTypeService grantTypeService;


    /**
     * 初始化业务分派逻辑,代替了if-else部分
     * key: 优惠券类型
     * value: lambda表达式,最终会获得该优惠券的发放方式
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        grantTypeMap.put(GrantTypeEnum.RED_PAPER.getKey(), resourceId -> grantTypeService.redPaper(resourceId));
        grantTypeMap.put(GrantTypeEnum.SHOPPING.getKey(), resourceId -> grantTypeService.shopping(resourceId));
        grantTypeMap.put(GrantTypeEnum.QQ_VIP.getKey(), resourceId -> grantTypeService.QQVip(resourceId));
    }

    public String getResult(Integer resourceType) {
        // Controller根据 优惠券类型resourceType、编码resourceId 去查询 发放方式grantType
        Function<Integer, String> result = grantTypeMap.get(resourceType);
        if (result != null) {
            // 传入resourceId 执行这段表达式获得String型的grantType
            return result.apply(resourceType);
        }
        return "查询不到该优惠券的发放方式";
    }
}
